const mixin = require("../../mixins");
Component({
	behaviors: [mixin],
	data: {
		children: [],
		sort: 0,
		select: 0,
		basicsTag: [],
	  loading:false,
		trackingParams: ""
	},

	properties: {
		mf_data: Object,
		customAppear: Boolean,
		type: String,
		isSp: Boolean,
	},
	async attached() {
		let page = getCurrentPages();
		let {
			utoolsClassGoodsLists,
			basicsTag,
			isBasicsTag = false,
			navName,
			getTsBySku,
			getGoodsDetailNew,
			isTs = null,
			tsStartStatus=null,
			tsActId,
			isPlp=false
		} = page[page.length - 1].data;
		let list = JSON.parse(JSON.stringify(utoolsClassGoodsLists)) ;
		let { mf_data } = this.properties;
		let { children, trackingParams } = mf_data;

		if (isTs) {
			children= [];
			for (let i = 0; i < list.length; i++) {
				let d = {};
				const frontCustomParameters = list[i]?.frontCustomParameters ? JSON.parse(list[i].frontCustomParameters) : null;
				if (list[i].approveStatus != "onsale" || !tsStartStatus) {
					list[i].frontQty = 0;
				}
				
				if (!d.goodsStatus && list[i].approveStatus != 'onsale') {
					d.goodsStatus = 1;
				}
				if (!d.goodsStatus && frontCustomParameters?.intentCheckMark == 1) {
					d.goodsStatus = 2;
				}
				if (!d.goodsStatus && list[i].frontQty < 6 && list[i].frontQty) {
					d.goodsStatus = 4;
				}
				
				d.curPrice = list[i].price;
				d.price =   this.moneyFormat(list[i].price);
				// d.price = Number(item?.price) ;
				d.title_EN = frontCustomParameters?.className;
				d.mainUrl = list[i]?.hoverUrl;
				d.title_CH = list[i]?.subtitle;
				d.goods = list[i];
				let isLevel = await  this.checkGoodsPromotion(d.goods)
				d.isLevel = isLevel.success
				children.push(d)
			}
		} else {
			if (list) {
				for (let i = 0; i < children.length; i++) {
					let goods = list.filter(it => it.itemId == children[i].itemId)[0]

					children[i].goodsStatus = 0;
					if (goods) {
						let isLevel = await  this.checkGoodsPromotion(goods)
						children[i].isLevel = isLevel.success
						goods = JSON.parse(JSON.stringify(goods));
						// goods.frontQty = 0;
						const frontCustomParameters = goods?.frontCustomParameters ? JSON.parse(goods.frontCustomParameters) : null;
						goods.isC2bGoods = false;
						children[i].isC2bGoods = false;
						if(frontCustomParameters && frontCustomParameters['c2bGoods'] == 1){
							children[i].isC2bGoods = true;
							goods.isC2bGoods = true;
						}
						if (goods.approveStatus != "onsale") {
							goods.frontQty = 0;
						}

						if (!children[i].goodsStatus && goods.approveStatus != 'onsale') {
							children[i].goodsStatus = 1;
						}
						if (!children[i].goodsStatus && frontCustomParameters?.intentCheckMark == 1) {
							children[i].goodsStatus = 2;
						}
						if (!children[i].goodsStatus && goods.frontQty < 6 && goods.frontQty) {
							children[i].goodsStatus = 4;
							// item.goodsStatus =  goods.frontQty< 1 ? 3 : 4
						}
						let p = goods?.price || children[i].curPrice;
						children[i].price = this.moneyFormat(p)
						children[i].frontCustomParameters = frontCustomParameters;
						
						children[i].title_EN = frontCustomParameters?.className || children[i].title_EN;
						//	useApiImg: true:使用接口图片/false:utools图片
						if(!children[i]?.useApiImg && children[i]?.customImg){
							children[i].mainUrl = children[i].customImg;
						}else{
							children[i].mainUrl = goods?.hoverUrl || children[i].mainUrl;
						}
						// children[i].mainUrl = goods?.hoverUrl || children[i].mainUrl;
						children[i].title_CH = goods?.subtitle || children[i].title_CH;
					} else {
						children[i].goodsStatus = 1
						let p = await this.moneyFormat(children[i]?.curPrice)
						goods = {
							price: p,
							status: 1,
							frontQty: 0,
							itemId: children[i].itemId,
							valueId: children[i].valueId || null,
							btnText: '查看详情'
						}
						children[i].title_EN = children[i].title_EN || "";
						children[i].price = Number(children[i].curPrice) ;
					}
					children[i].goods = goods;
				}
			}
		}
		this.setData({
			children,
			dchildren: children,
			basicsTag: basicsTag || [],
			isBasicsTag: isBasicsTag || "",
			tsActId,
			trackingParams: trackingParams || ""
		});
		
		if(isPlp) {
			page[page.length - 1].$vm.clossLoading();
		}
	
		page[page.length - 1].$vm.setHasMore && page[page.length - 1].$vm.setHasMore(children.length)
	},
	timer: null,
	methods: {
		
		async checkGoodsPromotion(item){
			
		  try{
			const api = getApp().globalData.api;
			let customerInfo = wx.getStorageSync('customerInfo');
			let merchantInfo = wx.getStorageSync('merchantInfo');
		    let memberDetails = wx.getStorageSync('memberDetails') || '';
		    if (!memberDetails || !item.valueId) {
		      return { success: false, msg: "当前等级不足，无法加购", data: null };
		    }
		    const json = await api.goodsPromotion({
		        method: 'GET',
		        query: {
		          price: item.price
		        }
		      },
		      merchantInfo.cloudMerchantId,
		      merchantInfo.cloudMerchantStoreId,
		      item.itemId,
		      item.valueId
		    );
		    if (json.code === 1000) {
		      let data = json.data;
		      let tempPromotionArr = data;
		      for (let t in tempPromotionArr) {
		        const tagItem = tempPromotionArr[t];
		        if (getApp().isDuringDate(tagItem.beginTime, tagItem.endTime)) {
		          if (tagItem.promotionType == 'forward_purchase') {
		            // 允许所有人购买
		            if (!tagItem.groupIds && !tagItem.memberLevelIds) {
		              return { success: true, msg: "可以加购", data: tagItem };
		            } else if (!!tagItem.memberLevelIds && tagItem.memberLevelIds.indexOf(memberDetails.memberLevelId) !== -1 || (!!tagItem.groupIds && tagItem.groupIds.indexOf(customerInfo.groupId) !== -1)) {
		              return { success: true, msg: "可以加购", data: tagItem };
		            } else if (!!tagItem.memberLevelIds && tagItem.memberLevelIds.indexOf(memberDetails.memberLevelId) == -1) {
		              return { success: false, msg: "当前等级不足，无法加购", data: tagItem };
		            } else if (!!tagItem.groupIds && tagItem.groupIds.indexOf(customerInfo.groupId) == -1) {
		              return { success: false, msg: "当前等级不足，无法加购", data: tagItem };
		            }
		          }
		        }
		      }
		      return { success: true, msg: "可以加购", data: null };
		    }
		  }catch(e){
		    return { success: false, msg: "当前等级不足，无法加购", data: null };
		  }
		},
		moneyFormat(value, num) {
		  num = num > 0 && num <= 20 ? num : 2;
		  value = parseFloat(value)
		  value = value.toFixed(num) + ""
		  var valueArr = value.split(".")[0].split("").reverse()
		  var valueFloat
		  var flag
		  if (value.indexOf('.') !== -1) {
		    if (value.indexOf('.00') !== -1) {
		      flag = false
		    } else {
		      flag = true
		      valueFloat = value.split(".")[1];
		    }
		  }
		  var valueString = "";
		  for (var i = 0; i < valueArr.length; i++) {
		    valueString += valueArr[i] + ((i + 1) % 3 == 0 && (i + 1) != valueArr.length ? "," : "");
		  }
		  var money = valueString.split("").reverse().join("");
		  money = flag ? money + "." + valueFloat : money
		  if (money.indexOf('.00') !== -1) {
		    money = money.substring(0, money.length - 3)
		  }
		  return money
		},

		clickGoodsItem(e) {
		
			let {
				mf_data
			} = this.properties;
			const {
				item
			} = e.currentTarget.dataset
			const {tsActId =null} = this.data
			if (!item?.goods?.itemId || !item?.goods?.valueId) return;
			if (!this.timer) {
				this.timer = setTimeout(() => {
					this.timer = null;
					this.clickGoodsTrack(item, mf_data);
					let url = item.goods.itemId ?`/pages/item/item?id=${item.goods.itemId}&valueId=${item.goods.valueId}` :'/pages/GTR/item?id=' + item.goods.id
					if(tsActId) {
						url = url + `&tsActId=${tsActId}`
					}
					wx.navigateTo({
						url: url
					})
				}, 200)
			}
		},
		//  商品点击埋点
		clickGoodsTrack(item, mf_data) {
			const {
				trackingParams,
				name1
			} = mf_data;
			try {
				const _trackingParams = trackingParams ? JSON.parse(trackingParams) : null;
				const module_name = (_trackingParams && _trackingParams.module_name) ? _trackingParams.module_name : "";
				const tab_name = (_trackingParams && _trackingParams.tab_name) ? _trackingParams.tab_name : "";
				this.triggerEvent('triggerComponent', {
					data: {
						item: item.goods,
						type: 'itemClick',
						module_name: module_name || name1,
						tab_name: tab_name
					}
				}, {
					bubbles: true,
					composed: true
				});
			} catch (e) {}
		},
		sortTap() {
		
			let {
				sort,
				dchildren
			} = this.data
			this.data.sort = sort == 2 ? 0 : sort + 1
			let children = this.sort()
			this.setData({
				sort: this.data.sort,
				children
			});
			let page = getCurrentPages();
			let trackData = {
				data: {
					tab_name: page[page.length - 1].data.navName,
					button_name: '价格排序',
				},
				name: 'PLPClick',
				type: 'click'
			}
			this.triggerEvent('triggerComponent', {
				data: {
					trackData: JSON.stringify(trackData),
					type: 'track'
				}
			}, {
				bubbles: true,
				composed: true
			});
		},
		selectTap() {
		
			let {
				select,
				dchildren
			} = this.data
			this.data.select = select == 1 ? 0 : select + 1
			let children = this.select()
			let page = getCurrentPages();
			page[page.length - 1].setData({
				hasMore: children.length
			})
			this.setData({
				select: this.data.select,
				children
			});
			let trackData = {
				data: {
					tab_name: page[page.length - 1].data.navName,
					button_name: select ? '关闭只看可购' : '开启只看可购',
				},
				name: 'PLPClick',
				type: 'click'
			}
			this.triggerEvent('triggerComponent', {
				data: {
					trackData: JSON.stringify(trackData),
					type: 'track'
				}
			}, {
				bubbles: true,
				composed: true
			});
		},
		sort() {
			let {
				sort,
				children,
				dchildren
			} = this.data
			let c = children.slice();
			if (sort > 0 && children.length) {
				c.sort(function(a, b) {
					if (sort == 2) {
						return b.curPrice - a.curPrice
					} else {
						return a.curPrice - b.curPrice
					}
				})
			} else {
				c = dchildren
			}
			return c
		},

		select() {
			let {
				select,
				dchildren,
				children
			} = this.data
			let {
				mf_data
			} = this.properties
			if (select > 0 && children.length) {
				let c1 = children.slice();
				let c2 = children.slice();
				c1 = c1.filter(item => {
					return (!item.goods.activitySelection && item.goods.frontQty && item.goods.approveStatus == "onsale" && item.isLevel)
				})
				// c2 = c2.filter(item => {
				// 	return !(!item.goods.activitySelection && item.goods.frontQty && item.goods.approveStatus == "onsale" ) && item.isLevel 
				// })
				this.data.children =c1
			} else {
				let children = this.sort()
				this.data.children = children
			}
			return this.data.children
		},
		clickAddCart(e) {
			const {
				item
			} = e.currentTarget.dataset

			if (!this.timer) {
				this.timer = setTimeout(async () => {
					this.timer = null;
					//这里是给home.vue发的加购事件
					this.triggerEvent('onAddCart', {
						data: item.goods
					}, {
						bubbles: true,
						composed: true
					});
					this.triggerEvent('triggerComponent', {
						data: {
							item: item.goods,
							type: 'addCartClick'
						}
					}, {
						bubbles: true,
						composed: true
					});
				}, 200)

			}
		}
	}
});
